<?php
declare (strict_types = 1);

namespace app\command;

use app\model\AdminMenu;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;

class AdminMenuCommand extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('my:AdminMenu')
            ->setDescription('写入 admin_menu 表初始化数据');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $output->writeln('start');
        $output->writeln('');

        // 菜单只支持二级菜单
        // 除了 $root_menus[index]['pid']，$menus[index]['pid'] 都是上级菜单的 title
        $pid        = 0;
        $rank       = 0;
        $is_show    = 1;
        $fields     = ['title', 'uri', 'pid', 'rank', 'is_show'];
        $root_menus = [
            ['系统设置', '#', $pid, $rank, $is_show],
        ];
        $menus      = [
            ['菜单', 'admin/menu/index', '系统设置', $rank, $is_show],
            ['系统参数', 'admin/config/index', '系统设置', $rank, $is_show],
            ['管理员', 'admin/user/index', '系统设置', $rank, $is_show],
            ['角色', 'admin/role/index', '系统设置', $rank, $is_show],
            ['操作日志', 'admin/action-log/index', '系统设置', $rank, $is_show],
            ['登录日志', 'admin/user-login-log/index', '系统设置', $rank, $is_show],
            ['访问权限', 'admin/permission/index', '系统设置', $rank, $is_show],
        ];

        foreach($root_menus as $menu){
            [$title, $uri, $pid, $rank, $is_show] = $menu;
            $adminMenu = AdminMenu::where('title', $title)->findOrEmpty();
            //dump(AdminMenu::getLastSql());
            if ($adminMenu->isExists())
            {
                $output->writeln("{$title}:{$uri} 已存在");
                continue;
            }

            AdminMenu::generateLog($pid, $rank, $title, $uri, $is_show);
            $output->writeln("{$title}:{$uri} 写入成功");
        }

        foreach($menus as $menu){
            [$title, $uri, $pid, $rank, $is_show] = $menu;
            $adminMenu = AdminMenu::where('title', $title)->where('uri', $uri)->findOrEmpty();
            //dump(AdminMenu::getLastSql());
            if ($adminMenu->isExists())
            {
                $output->writeln("{$title}:{$uri} 已存在");
                continue;
            }

            $adminMenu2 = AdminMenu::where('title', $pid)->findOrEmpty();
            $pid        = 0;
            if ($adminMenu2->isExists()) $pid = $adminMenu2->id;

            AdminMenu::generateLog($pid, $rank, $title, $uri, $is_show);
            $output->writeln("{$title}:{$uri} 写入成功");
        }

        $output->writeln('');
        $output->writeln('end');
    }
}
